package com.loc.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.loc.dao.RolesDao;
import com.loc.dao.UsersDao;
import com.loc.pojo.Users;

public class MyUserDetailServiceImpl implements UserDetailsService {
	@Autowired
	private UsersDao usersDao;
	@Autowired
	private RolesDao rolesDao;
	private DataSource dataSource;
	private UserCache userCache;

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public UserCache getUserCache() {
		return userCache;
	}

	public void setUserCache(UserCache userCache) {
		this.userCache = userCache;
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		Users users = null;
		try {
			users = this.usersDao.findByName(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (users == null) {
			throw new UsernameNotFoundException(username);
		}
		Collection<GrantedAuthority> grantedAuthorities = null;
		try {
			grantedAuthorities = obtionGrantedAuthorities(users);
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean enables = true;
		boolean accountNonExpried = true;
		boolean credentialsNonExpried = true;
		boolean accountNonLocked = true;
		User userdetail = new User(users.getUser_account(), users.getUser_password(),
				enables, accountNonExpried, credentialsNonExpried,
				accountNonLocked, grantedAuthorities);
		return userdetail;
	}

	private Set<GrantedAuthority> obtionGrantedAuthorities(Users users)
			throws Exception {
		Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
		List<String> list = rolesDao.findAllByUser(users);
		for (String res : list) {
			authSet.add(new GrantedAuthorityImpl(res));
		}
		return authSet;
	}
}
